﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Fish.Models;
using Fish.DAL;
using System.Net.Mail;

namespace Fish.Controllers
{
    /* Handles the creation/editing of the event information page. Also handles invitiation of event guests.
     */
    [Authorize]
    public class EventInfoController : Controller
    {
        private FishContext db = new FishContext();

        // GET: /EventInfo/
        public ActionResult Index()
        {
            return RedirectToAction("AccessDenied", "Error");
            var eventinfoes = db.EventInfoes.Include(e => e.Event);
            return View(eventinfoes.ToList());
        }

        // GET: /EventInfo/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            EventInfo eventinfo = db.EventInfoes.Where(e => e.EventsID == id).FirstOrDefault();
            if (eventinfo == null)
            {
                return RedirectToAction("Expired", "Error");
                return HttpNotFound();
            }
            Session["eventID"] = id;
            ViewBag.eventID = id;
            return View(eventinfo);
        }

        //Get the event image to display it
        [HttpGet]
        public ActionResult ViewImage(int id)
        {
            //    System.Diagnostics.Debug.WriteLine("User: " + id);
            EventInfo eventInfo = db.EventInfoes.Where(e => e.EventsID == id).FirstOrDefault();
            if (eventInfo != null)
            {
                byte[] buffer = eventInfo.EventImage;
                if(buffer!=null)
                    return File(buffer, "image/jpg", string.Format("{0}.jpg", id));
            }
            return File("~/Content/Images/no-image.gif", "image/jpg", string.Format("{0}.jpg", id));
        }

        // GET: /EventInfo/Create
        public ActionResult Create()
        {
            if (Session["eventID"] != null)
            {
                Events thisEvent = db.Events.Find(int.Parse(Session["eventID"].ToString()));
                ViewBag.EventName = thisEvent.Name;
                return View();
            }
            else
            {
                return RedirectToAction("Create", "Events");
            }
        }

        // POST: /EventInfo/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Description,MaximumGuests,Image,Address,StartDate,EndDate,Created,Modified")] EventInfo eventinfo, HttpPostedFileBase uploadedImage)
        {
                byte[] imageBytes = null;

                if (uploadedImage != null)
                {

                    int imageLength = uploadedImage.ContentLength;
                    imageBytes = new byte[imageLength];
                    uploadedImage.InputStream.Read(imageBytes, 0, imageLength);
                }
                eventinfo.EventImage = imageBytes;
                if (eventinfo.EndDate.Year != 1 && eventinfo.StartDate.CompareTo(eventinfo.EndDate) > 0)
                {
                 ModelState.AddModelError("Date error", "start date must be before end date");
                  //  ViewBag.Error = "start date must be before end date";

                    return View(eventinfo);
                }
                else
                {
                    if (eventinfo.EndDate.Year == 1)
                    {
                        eventinfo.EndDate = DateTime.Parse("1/1/1");
                    }
                    if (eventinfo.MaximumGuests <1)
                    {
                        eventinfo.MaximumGuests = -1;
                    }
                    System.Diagnostics.Debug.WriteLine("EVENT ID: " + Session["eventID"]);
                    eventinfo.EventsID = int.Parse(Session["eventID"].ToString());
                    db.EventInfoes.Add(eventinfo);
                    db.SaveChanges();
                    return RedirectToAction("Index", "EventUserRelations");

                }
            
            if (Session["eventID"] != null)
            {
                Events thisEvent = db.Events.Find(int.Parse(Session["eventID"].ToString()));
                ViewBag.EventName = thisEvent.Name;
                ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventinfo.EventsID);
                return View(eventinfo);
            }
            else
            {
                return RedirectToAction("Create", "Events");
            }
        }

        public ActionResult Invite(int id)
        {
            return View();
        }
        public bool IsValid(string emailaddress)
        {
            try
            {
                MailAddress m = new MailAddress(emailaddress);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }
        //Method used to send emails containing event links to specified addresses.
        [HttpPost]
        public ActionResult Invite(string emails)
        {
            if (emails == "" || emails.Length < 2)
            {
                return RedirectToAction("Details", "EventInfo", new { id = Session["eventID"] });
            }
            string[] emailList = emails.Split(';');
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            SmtpServer.UseDefaultCredentials = false;
            SmtpServer.Credentials = new NetworkCredential("samakazahabya@gmail.com", "goldfish369");
            SmtpServer.EnableSsl = true;
            SmtpServer.Port = 587;
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("samakazahabya@gmail.com");
            foreach(string em in emailList){
                if (!IsValid(em)) {
                    continue;
                }
                mail.To.Add(em);
                mail.Subject = "Event Invitation";
                mail.Body = "You have been invited to the following event \n http://localhost:39775/EventInfo/Details/" + Session["eventID"];

                SmtpServer.Send(mail);
            }
            return RedirectToAction("Details", "EventInfo", new { id = Session["eventID"] });
        }


        // GET: /EventInfo/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EventInfo eventinfo = db.EventInfoes.Find(id);
            if (eventinfo == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventinfo.EventsID);
            return View(eventinfo);
        }

        // POST: /EventInfo/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,EventsID,Description,Address,StartDate,EndDate,MaximumGuests,Created,Modified")] EventInfo eventinfo, String eventName)
        {
            System.Diagnostics.Debug.WriteLine(" NAME:: " + eventName);
            if (ModelState.IsValid)
            {
                Events eventz = db.Events.Find(eventinfo.EventsID);
                eventz.Name = eventName;
                db.Entry(eventinfo).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", "EventInfo", new { id = eventinfo.EventsID });
            }
            ViewBag.EventsID = new SelectList(db.Events, "ID", "Name", eventinfo.EventsID);
            return View(eventinfo);
        }

        // GET: /EventInfo/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction("PageNotFound", "Error");

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            EventInfo eventinfo = db.EventInfoes.Find(id);
            if (eventinfo == null)
            {
                return RedirectToAction("Expired", "Error");

                return HttpNotFound();
            }
            return View(eventinfo);
        }

        // POST: /EventInfo/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            EventInfo eventinfo = db.EventInfoes.Find(id);
            db.EventInfoes.Remove(eventinfo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        public ActionResult currentEvent()
        {
            int eventID;
            if (Session["eventID"] != null)
                eventID = int.Parse(Session["eventID"].ToString());
            else
                eventID = -1;
            return RedirectToAction("Details", new { id = eventID });
        }
    }
}
